const Service = require('uni-cloud-router').Service;

module.exports = class AddressService extends Service {
  constructor(ctx) {
    super(ctx);
    this.collection = this.db.collection('account_book');
    this.dbCmd = this.db.command;
  }

  async add(params) {
	params = Array.isArray(params) ? params : [params]
	params = params.map(({ creatTime, modelName, price, number }) => {
	  return {
	    creatTime,
	    modelName,
	    price,
	    number,
		isDelete: 0
	  };
	});
    return this.collection.add(params);
  }

  remove({ _id }) {
    return this.collection.doc(_id).update({isDelete: 1});
  }

  async update(params) {
    let { _id, creatTime, modelName, price, number } = params;
    this.ctx.data.is_default && (await this._cancelDefault());
    return this.collection.doc(_id).update({
      creatTime,
      modelName,
      price,
      number,
    });
  }

  async list({ startTime, endTime }) {
    let where = {isDelete: this.dbCmd.eq(0)};
    if (startTime && endTime) {
      where = this.dbCmd.and(where, { creatTime: this.dbCmd.lte(endTime) }, { creatTime: this.dbCmd.gte(startTime) });
    }
    return this.collection.where(where).orderBy('creatTime', 'desc').get();
  }

  async page({ page = 1, size = 10, startTime, endTime }) {
    let where = {isDelete: this.dbCmd.eq(0)};
    if (startTime && endTime) {
      where = this.dbCmd.and(where, { creatTime: this.dbCmd.lte(endTime) }, { creatTime: this.dbCmd.gte(startTime) });
    }
    return this.collection
      .where(where)
	  .orderBy('creatTime', 'desc')
      .skip((page - 1) * size)
      .limit(size)
      .get();
  }

  async detail(params) {
    const id = params.id || params._id;
    const res = await this.collection.doc(id).get();
    return { data: res.data[0], code: 200 };
  }
};
